package com.yami.shop.common.config;

import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbMakerConfigException;
import org.lionsoul.ip2region.DbSearcher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Configuration
public class Ip2RegionConfig {

    @Bean
    public DbSearcher dbSearcher() throws DbMakerConfigException, IOException {
        DbConfig dbConfig = new DbConfig();

//        String path = new ClassPathResource("/ip2region.db").getPath();

        InputStream inputStream = Ip2RegionConfig.class.getResourceAsStream("/ip2region.db");

        return new DbSearcher(dbConfig, toByteArray(inputStream));
    }

    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }
}
